import React, { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';

interface SimpleRichTextEditorProps {
  value: string;
  onChange: (html: string) => void;
  height?: number;
  placeholder?: string;
}

const SimpleRichTextEditor: React.FC<SimpleRichTextEditorProps> = ({
  value,
  onChange,
  height = 400,
  placeholder = '请输入内容...'
}) => {
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState(value);

  // 简化的工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    toolbarKeys: [
      'headerSelect',
      'bold',
      'italic',
      'underline',
      '|',
      'color',
      'bgColor',
      '|',
      'fontSize',
      '|',
      'bulletedList',
      'numberedList',
      '|',
      'justifyLeft',
      'justifyRight',
      'justifyCenter',
      'justifyJustify',
      '|',
      'insertLink',
      'uploadImage',
      '|',
      'undo',
      'redo'
    ]
  };

  // 简化的编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder,
    MENU_CONF: {
      uploadImage: {
        // 使用base64方式处理图片
        customUpload(file: File, insertFn: any) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const result = e.target?.result as string;
            if (result) {
              insertFn(result, file.name, '');
            }
          };
          reader.readAsDataURL(file);
          return false; // 阻止默认上传
        }
      }
    }
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 同步 value 到 html
  useEffect(() => {
    if (value !== html) {
      setHtml(value);
    }
  }, [value]);

  // 同步 html 到 onChange (只在编辑器内容变化时调用)
  const handleEditorChange = (editor: IDomEditor) => {
    const newHtml = editor.getHtml();
    if (newHtml !== html) {
      setHtml(newHtml);
      onChange(newHtml);
    }
  };

  return (
    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={handleEditorChange}
        mode="default"
        style={{ height }}
      />
    </div>
  );
};

export default SimpleRichTextEditor; 